package com.dahua.messagesyncbj.runner;

import com.alibaba.fastjson2.JSON;
import com.dahua.messagesyncbj.entity.Fault;
import com.dahua.messagesyncbj.entity.Status;
import com.dahua.messagesyncbj.pojo.SyncMessage;
import com.dahua.messagesyncbj.service.EquipmentService;
import com.dahua.messagesyncbj.service.FaultService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class SyncHandleRunner implements Runnable {

    @Resource
    private FaultService faultService;
    @Resource
    private EquipmentService equipmentService;

    @Resource
    private RedissonClient redissonClient;

    @Override
    public void run() {
        /*  */
    }

    public void handle(List<ConsumerRecord<String, String>> consumerRecords) {

        List<SyncMessage> faults = new ArrayList<>();

        for (ConsumerRecord<String, String> item : consumerRecords) {
            SyncMessage syncMessage = JSON.parseObject(item.value(), SyncMessage.class);
            switch (syncMessage.getType()) {
                case 1:
                    faults.add(syncMessage);
                    break;
                default:
                    break;
            }
        }

        if (!faults.isEmpty()) {
            this.handleFault(faults);
        }

    }


    public void handleFault(List<SyncMessage> syncMessage) {
        for (SyncMessage item : syncMessage) {
            Fault fault = JSON.parseObject(item.getData().toString(), Fault.class);
            switch (item.getOperation()) {
                case 1:
                    faultService.insertFault(fault, fault.getSensorType());
                    break;
                case 2:
                    faultService.recover(fault);
                    break;
                case 3:
                    faultService.fixAllFault(fault.getManufactureId(), fault.getEndTime().getTime());
                    break;
            }
        }
    }
}
